package com.hemi.rhet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;

import org.apache.http.ParseException;
import org.apache.http.cookie.Cookie;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;

import com.hemi.rhet.util.ApplicationContext;
import com.hemi.rhet.util.HttpUtil;
import com.hemi.rhet.util.OSInfoUtil;

public class PostDetailGuide extends Activity {
	private Handler mHandler = new Handler();   
	   private String imageContainerId = null;
	    private String fileIdItemName = null;
	    WebView  mWebView  = null;
	    private static final int SCTU = Menu.FIRST;
	    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Cookie sessionCookie = (Cookie) ApplicationContext.getData(Constants._COOKIE_KEY);//这里的cookie就是上面保存的cookie    
        CookieSyncManager.createInstance(this);  
        CookieManager cookieManager = CookieManager.getInstance();  
        if (sessionCookie != null) {  
            String cookieString = sessionCookie.getName() + "=" + sessionCookie.getValue() + "; domain=" + sessionCookie.getDomain();
            cookieManager.setCookie(ApplicationContext.DOMAIN, cookieString);
            CookieSyncManager.getInstance().sync();  
        } 
        setContentView(R.layout.post_detail);
           mWebView = (WebView) findViewById(R.id.postGuideView); 
//        savedInstanceState.geti
        Intent intent=getIntent();     
        WebSettings webSettings = mWebView.getSettings();   
        webSettings.setDefaultTextEncodingName("utf-8"); 
        webSettings.setSavePassword(false);   
        webSettings.setSaveFormData(false);   
        webSettings.setJavaScriptEnabled(true);   
        webSettings.setSupportZoom(false);   
       // webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        mWebView.addJavascriptInterface(new JavaScriptInterface2URL( ), "android_url"); 
        mWebView.addJavascriptInterface(new JavaScriptInterfaceCallCarema(), "android_carema");   
        mWebView.addJavascriptInterface(new JavaScriptInterface4POSTDataHttpClient(), "android_post");   
        
        webSettings.setBuiltInZoomControls(false);
        mWebView.setWebChromeClient(new YhWebChromeClient());  
//        mWebView.setWebViewClient(new MyWebViewClient());
        mWebView.setInitialScale(100);//初始显示比例100%
        mWebView.loadUrl(intent.getStringExtra(Constants._POST_GUIDE_KEY_)); 
        
    }
    
    
      class JavaScriptInterface2URL {
        public void clickOnAndroid(final String url) {   
        	 Cookie sessionCookie = (Cookie) ApplicationContext.getData(Constants._COOKIE_KEY);//这里的cookie就是上面保存的cookie    
             CookieSyncManager.createInstance(PostDetailGuide.this);  
             CookieManager cookieManager = CookieManager.getInstance();  
             if (sessionCookie != null) {  
                 String cookieString = sessionCookie.getName() + "=" + sessionCookie.getValue() + "; domain=" + sessionCookie.getDomain();
                 cookieManager.setCookie(ApplicationContext.DOMAIN, cookieString);
                 CookieSyncManager.getInstance().sync();  
             }
       	String history_url = ApplicationContext.DOMAIN+OSInfoUtil.trAppNameUrl(url);
       	if(history_url.indexOf("?")==-1)
       	{
       		history_url = history_url+"_android";
       	}
       	 mWebView.loadUrl(history_url); 
        }   

        
    }
    
    

  class JavaScriptInterface4POSTDataHttpClient {
//	private Context contxt = null;
//	private WebView mWebView = null;
//	public JavaScriptInterface4POSTDataHttpClient(Context contxt, WebView mWebView)
//	
//	{
//		this.mWebView = mWebView;
//		this.contxt = contxt;
//	}
	
    public void clickOnAndroid(final String url,final String content) {  
    	 mHandler.post(new Runnable() {   
             public void run() { 
        	 String urlStr = new StringBuffer(ApplicationContext.DOMAIN+url+"_android").toString();
      		 	 HashMap mapparams = new HashMap();
      		 	try {
      		 		JSONObject d = new JSONObject(content);
					Iterator it = d.keys();
					while(it.hasNext())
					{
						String key  =(String)it.next();
						String value = (String)d.get(key);
						mapparams.put(key, value);
					}
					HashMap rcontent = HttpUtil.postUrl4ResultMap(urlStr, mapparams);
					if(rcontent!=null && rcontent.get("code").equals("1"))
					{
						Toast.makeText(PostDetailGuide.this, "操作成功！",Toast.LENGTH_SHORT).show();    
						
			        	 Cookie sessionCookie = (Cookie) ApplicationContext.getData(Constants._COOKIE_KEY);//这里的cookie就是上面保存的cookie    
			             CookieSyncManager.createInstance(PostDetailGuide.this);  
			             CookieManager cookieManager = CookieManager.getInstance();  
			             if (sessionCookie != null) {  
			                 String cookieString = sessionCookie.getName() + "=" + sessionCookie.getValue() + "; domain=" + sessionCookie.getDomain();
//			                 cookieManager.setCookie(Constants._COOKIE_KEY, cookieString);  
			                 cookieManager.setCookie(ApplicationContext.DOMAIN, cookieString);
			                 CookieSyncManager.getInstance().sync();  
			             }
//			             history_url = ApplicationContext.DOMAIN+OSInfoUtil.trAppNameUrl(mapparams.get("_redirectUrl_")+"_android");
						 mWebView.loadUrl("http://192.168.1.118:8080/aiu/post/myPostes_android");   
					}else{
						Toast.makeText(PostDetailGuide.this, "操作失败！",Toast.LENGTH_SHORT).show();   
					}
				} catch (JSONException e) {
					e.printStackTrace();
				} catch (ParseException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} 
             }
    	 });  
    }


}

    public boolean callCarema(){
    	Intent i= new Intent();
		i.setClass(PostDetailGuide.this, PhotoUpload.class);
		startActivityForResult(i,SCTU);
		return true;
    }
    
    
    final class JavaScriptInterfaceCallCarema {   
        public void clickOnAndroid(final String imageContainerIdp,final String fileIdItemNamep) { 
//        	imageContainerId  = imageContainerIdp;
//        	fileIdItemName = fileIdItemNamep;
//        	Intent i= new Intent();
//    		i.setClass(WebViewDemo.this, PhotoUpload.class);
//    		startActivityForResult(i,SCTU);
    		
    		
            mHandler.post(new Runnable() {   
                public void run() {   
                	imageContainerId  = imageContainerIdp;
                	fileIdItemName = fileIdItemNamep;
                	callCarema();
                }   
            });   
        }   
    }   
    
    
    @Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
			if(data==null)
			{
				ParamUtil.showMessage(PostDetailGuide.this, "无图片选择！");
				return ;
			}
			String message = (String)data.getExtras().get("imageInfo");
			HashMap ham = ParamUtil.stringTomsgMap(message);
			mWebView.loadUrl("javascript:createImageSrc('"+ham.get("fileId")+"','"+ham.get("fileName")+"','"+imageContainerId+"','"+fileIdItemName+"')");
	}
    

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.post_detail, menu);
        return true;
    }
}
